# -*- coding: UTF8 -*-
# -*- coding: UTF8 -*-
import random
import string

from xmpp import *
from Queue import *
import Unit
import DF
import Behaviour
import ACLMessage


class CreationError(Exception):
    def __init__(self):
        Exception.__init__(self)
class NotValidName(CreationError):
    def __init__(self):
        Exception.__init__(self)
class NotValidType(CreationError):
    def __init__(self):
        Exception.__init__(self)
class NotValidGoal(CreationError):
    def __init__(self):
        Exception.__init__(self)
class NotCreatePermision(CreationError):
    def __init__(self):
        Exception.__init__(self)
class NotSupervisor(CreationError):
    def __init__(self):
        Exception.__init__(self)
class JoinError(Exception):
    def __init__(self):
        Exception.__init__(self)
class PaswordNeeded(JoinError):
    def __init__(self):
        pass
class MembersOnly(JoinError):
    def __init__(self):
        Exception.__init__(self)
class BanedUser(JoinError):
    def __init__(self):
        Exception.__init__(self)
class NickNameConflict(JoinError):
    def __init__(self):
        Exception.__init__(self)
class MaximumUsers(JoinError):
    def __init__(self):
        pass
class LockedOrganization(JoinError):
    def __init__(self):
        Exception.__init__(self)
class MemberOfFederation(JoinError):
    def __init__(self):
        Exception.__init__(self)
class Unavailable(Exception):
    def __init__(self):
        Exception.__init__(self)
class UnavailableFunction(Exception):
    def __init__(self):
        Exception.__init__(self)
class DestroyError(Exception):
    def __init__(self):
        Exception.__init__(self)
class NotValidUnit(Exception):
    def __init__(self):
        Exception.__init__(self)
class LastOwner(Exception):
    def __init__(self):
        Exception.__init__(self)
class LockedUnit(JoinError):
    def __init__(self):
        JoinError.__init__(self)
class DFException(Exception):
    def __init__(self):
        Exception.__init__(self)
class NotAllowed(Exception):
    def __init__(self):
        Exception.__init__(self)

class Organization(Unit.Unit):

  def __init__(self,agent, nick, name, type=None, goalList=None, agentList=[], contentLanguage="sl",create=True):
    Behaviour.Behaviour.__init__(self)
    self.myAgent=agent
    self.name = name
    self.type = type
    self.goalList = goalList
    self.agentList = agentList
    self.contentLanguage = contentLanguage
    self.platform = self.myAgent.getSpadePlatformJID()
    self.muc_name = self.myAgent.getMUC()
    self._roster = {}
    self.nick=nick
    self.create=create
    id_base = "".join([string.ascii_letters[int(random.randint(0,len(string.ascii_letters)-1))] for a in range(5)]) #@UnusedVariable
    self.ID = str(name) + str(self.myAgent.getAID().getName()) + id_base
    self.state="unavailable"
    self.UnavailableMsg="Organization"
    self.members=[]
    self.owner=False
    self.orgOwner=[]
    self.parent=""
    self.requestBehaviour=None


  def setup(self):
      pass

  def myCreate(self):
      if not self.checkGoal(self.goalList):
          return NotValidGoal
      elif not self.checkType():
          return NotValidType
      elif not self.testRoomName():
          return NotValidName
      elif not self.createRoom():
          return CreationError
      else:
          self.state="available"
          if self.agentList!=[]:
        #enviando invitaciones
            self.invite(self.agentList)
     #registrando en el DF
          dad = DF.DfAgentDescription()
          dad.setAID(self.myAgent.getAID())
          search = self.myAgent.searchService(dad)
          if search:
              dad=search[0]
              d = DF.DfAgentDescription()
              d.setAID(self.myAgent.getAID())
              self.myAgent.deregisterService(d)
          else:
              dad = DF.DfAgentDescription()
              dad.setAID(self.myAgent.getAID())
          ds = DF.ServiceDescription()
          ds.setType("ORGANIZATION")
          ds.setName(self.name)
          dad.addService(ds)
          res = self.myAgent.registerService(dad)
          cont=0
          while not res and cont<3:
                 res = self.myAgent.registerService(dad)
                 cont=cont+1
          if not res: return CreationError
          self.owner=True
          self.orgOwner=[self.myAgent.JID,self.myAgent.getDF().getName()]
          p = Presence(frm=self.name+"@"+self.muc_name)
          t = Behaviour.MessageTemplate(p)
          self.presenceBehaviour=self.PresenceBehaviour(self.muc_name,self.name,self.nick,self)
          self.myAgent.addBehaviour(self.presenceBehaviour, t)
          if self.type=="Matrix" or self.type=="Federation":
              self.createTeam()
          return True


  def myJoin(self):
        #The Organization exists
      if not self.testOrganizationName():
        #The room no existe
        raise NotValidName
      else:
          code=self.myJoinRoom()
          if code!=True:
                    if code=="401":
                        return PasswordNeeded
                    if code=="407":
                        return MembersOnly
                    if code=="403":
                        return BanedUser
                    if code=="409":
                        return NickNameConflict
                    if code=="503":
                        return MaximumUsers
                    if code=="404":
                        return LockedOrganization
                #No es una organizacion
          else:
              self.state="available"
              info=self.getInfo()
              if info:
                  self.type = info["type"]
                  self.contentLanguage = info["contentLanguage"]
                  self.parent=""
                  self.goal=info["goal"]

              p = Presence(frm=self.name+"@"+self.muc_name)
              t = Behaviour.MessageTemplate(p)
              self.presenceBehaviour=self.PresenceBehaviour(self.muc_name,self.name,self.nick,self)
              self.myAgent.addBehaviour(self.presenceBehaviour, t)
              return True


  def testRoomName(self):
    ID="".join([string.ascii_letters[int(random.randint(0,len(string.ascii_letters)-1))] for a in range(5)])
    iq = Iq(frm=self.muc_name, attrs={"id":ID})
    t = Behaviour.MessageTemplate(iq)
    b=self.TestRoomNameBehaviour(ID,self.muc_name,self.name)
    self.myAgent.addBehaviour(b, t)
    b.join()
    return b.result






  class TestRoomNameBehaviour(Behaviour.OneShotBehaviour):
        def __init__(self,ID,muc_name,roomname):
            Behaviour.OneShotBehaviour.__init__(self)
            self.ID=ID
            self.result = False
            self.muc_name=muc_name
            self.roomname=roomname

        def _process(self):
           iq = Iq(to=self.muc_name,typ='get', attrs={"id":self.ID})
           query = Protocol('query',xmlns="http://jabber.org/protocol/disco#items")
           iq.addChild(node=query)
           self.myAgent.jabber.send(iq)
           msg = self._receive(True,10)
           if msg:
               if query:
                   self.result = True
                   items = msg.getQueryChildren()
                   for item in items:
                       if item.getAttr("jid") == str(self.roomname+"@"+self.muc_name):
                           self.result = False
               else:
                   self.result = False

  def testOrganizationName(self):
        l=self.myAgent.getOrganizationList()
        if self.name in l:
                return True
        return False







  def createRoom(self):
    ID="".join([string.ascii_letters[int(random.randint(0,len(string.ascii_letters)-1))] for a in range(5)])
    p = Presence(frm=self.name+"@"+self.muc_name+"/"+self.nick)
    t1 = Behaviour.MessageTemplate(p)
    b=self.CreateRoomBehaviour(ID,self.muc_name,self.name,self.nick,self.contentLanguage,self.type,self.goalList)
    self.myAgent.addBehaviour(b, t1)
    b.join()
    return b.result

  class CreateRoomBehaviour(Behaviour.OneShotBehaviour):
        def __init__(self,ID,muc_name,roomname,nick,contentLanguage,type,goal):
            Behaviour.OneShotBehaviour.__init__(self)
            self.result = False
            self.ID=ID
            self.nick=nick
            self.muc_name=muc_name
            self.name=roomname
            self.contentLanguage=contentLanguage
            self.type=type
            self.goal=goal

        def _process(self):
            p = Presence(to=self.name+"@"+self.muc_name+"/"+self.nick)
            x = Protocol("x", xmlns="http://jabber.org/protocol/muc")
            p.addChild(node=x)
            self.myAgent.jabber.send(p)
            msg=self._receive(True,10)
            if msg:
                if msg.getAttr("type")=="error":
                    print "Room creation is restricted"
                    self.result= False
                    return
            else:
                    self.result= False
                    return
            template= Iq(frm=self.name+"@"+self.muc_name, attrs={"id":self.ID})
            t = Behaviour.MessageTemplate(template)
            self.setTemplate(t)
            iq = Iq(to=self.name+"@"+self.muc_name,typ='get', attrs={"id":self.ID})
            query = Protocol('query',xmlns="http://jabber.org/protocol/muc#owner")
            iq.addChild(node=query)
            self.myAgent.jabber.send(iq)
            msg = self._receive(True,10)
            #para descartar los presence anteriores
            while msg and msg.getName()!="iq":
                msg = self._receive(True,10)

          #setting room configuration
            if not msg or msg.getAttr("type")=="error":
                print "No configuration is possible: "
                self.result= False
                return
            #falta por revisar!!!!
            iq = Iq(to=self.name+"@"+self.muc_name,typ='set', attrs={"id":self.ID})
            query = Protocol('query',xmlns="http://jabber.org/protocol/muc#owner")
            x=Node(tag="x", attrs={"xmlns":"jabber:x:data"," type":"submit"})
            resquery=msg.getQueryChildren()[0] #nos quedamos con el hijo de query
            if resquery: items = resquery.getTags("field")
            if resquery==None:
                print "No configuration is possible"
                self.result= False
            for item in items:
                value=None
                if item.getAttr("var") == "muc#roomconfig_lang":
                    value=self.contentLanguage
                if item.getAttr("var") == "muc#roomconfig_roomdesc":
                    value=self.type
                if item.getAttr("var") == "muc#roomconfig_roomtype":
                    value=self.name
                if item.getAttr("var") == "muc#roomconfig_roomname":
                    value=self.name
                if item.getAttr("var") == "muc#roomconfig_presencebroadcast":
                    value="moderator"
                if item.getAttr("var") == "muc#roomconfig_persistentroom":
                    value="1"
                if item.getAttr("var") == "muc#roomconfig_publicroom":
                    value="1"
                if item.getAttr("var") == "muc#roomconfig_moderatedroom":
                    value="1"
                if item.getAttr("var") == "muc#roomconfig_membersonly":
                    value="0"
                if item.getAttr("var") == "muc#roomconfig_passwordprotectedroom":
                    value="0"
                if item.getAttr("var") == "muc#roomconfig_whois":
                    value="moderators"
                if item.getAttr("var") == "muc#roomconfig_changesubject":
                    if self.type!="Flat":
                        value="0"
                    else:
                        value="1"
                if value:
                    node=Node(tag="field", attrs={"var":item.getAttr("var")})
                    valnode=Node(tag="value")
                    valnode.addData(value)
                    node.addChild(node=valnode)
                    x.addChild(node=node)
            query.addChild(node=x)
            iq.addChild(node=query)
            self.myAgent.jabber.send(iq)
            msg = self._receive(True,10)
            if msg and msg.getAttr("type")=="result": #comprobar mejor el mensaje que se devuelve
                #modifying the Room Subject
                m = Message(to=self.name+"@"+self.muc_name, typ="groupchat")
                sub = Node(tag="subject")
                sub.addData(str(self.goal))
                m.addChild(node=sub)
                self.myAgent.jabber.send(m)
                #añadimos al DF como owner de la organizacion
                iq = Iq(to=self.name+"@"+self.muc_name,typ='set', attrs={"id":self.ID})
                query = Protocol('query',xmlns="http://jabber.org/protocol/muc#admin")
                item= Node(tag="item", attrs={"affiliation":"owner","jid":self.myAgent.getDF().getName()})
                query.addChild(node=item)
                iq.addChild(node=query)
                self.myAgent.jabber.send(iq)
                if self.name not in self.myAgent.rooms:
                    self.myAgent.rooms.append(self.name)
                self.result= True
            else:
                self.result= False

  def createTeam(self):
    ID="".join([string.ascii_letters[int(random.randint(0,len(string.ascii_letters)-1))] for a in range(5)])
    p = Presence(frm="Team:"+self.name+"@"+self.muc_name+"/"+self.nick)
    t1 = Behaviour.MessageTemplate(p)
    b=self.CreateTeamBehaviour(ID,self.muc_name,self.name,self.nick,self.contentLanguage,self.goalList,self.agentList)
    self.myAgent.addBehaviour(b, t1)
    b.join()
    return b.result

  class CreateTeamBehaviour(Behaviour.OneShotBehaviour):
        def __init__(self,ID,muc_name,roomname,nick,contentLanguage,goal,agentList):
            Behaviour.OneShotBehaviour.__init__(self)
            self.result = False
            self.ID=ID
            self.nick=nick
            self.muc_name=muc_name
            self.name="Team:"+roomname
            self.parent=roomname
            self.contentLanguage=contentLanguage
            self.type="Team"
            self.goal=goal
            self.agentList=agentList

        def _process(self):
            p = Presence(to=self.name+"@"+self.muc_name+"/"+self.nick)
            x = Protocol("x", xmlns="http://jabber.org/protocol/muc")
            p.addChild(node=x)
            self.myAgent.jabber.send(p)
            msg=self._receive(True,10)
            if msg:
                if msg.getAttr("type")=="error":
                    print "Room creation is restricted"
                    self.result= False
                    return
            else:
                    self.result= False
                    return
            template= Iq(frm=self.name+"@"+self.muc_name, attrs={"id":self.ID})
            t = Behaviour.MessageTemplate(template)
            self.setTemplate(t)
            iq = Iq(to=self.name+"@"+self.muc_name,typ='get', attrs={"id":self.ID})
            query = Protocol('query',xmlns="http://jabber.org/protocol/muc#owner")
            iq.addChild(node=query)
            self.myAgent.jabber.send(iq)
            msg = self._receive(True,10)
            #para descartar los presence anteriores
            while msg and msg.getName()!="iq":
                msg = self._receive(True,10)

          #setting room configuration
            if not msg or msg.getAttr("type")=="error":
                print "No configuration is possible: "
                self.result= False
                return
            #falta por revisar!!!!
            iq = Iq(to=self.name+"@"+self.muc_name,typ='set', attrs={"id":self.ID})
            query = Protocol('query',xmlns="http://jabber.org/protocol/muc#owner")
            x=Node(tag="x", attrs={"xmlns":"jabber:x:data"," type":"submit"})
            resquery=msg.getQueryChildren()[0] #nos quedamos con el hijo de query
            if resquery: items = resquery.getTags("field")
            if resquery==None:
                print "No configuration is possible"
                self.result= False
            for item in items:
                value=None
                if item.getAttr("var"):
                    value=item.getAttr("value") #tomamos el valor
                if item.getAttr("var") == "muc#roomconfig_lang":
                    value=self.contentLanguage
                if item.getAttr("var") == "muc#roomconfig_roomdesc":
                    value=self.type
                if item.getAttr("var") == "muc#roomconfig_roomtype":
                    value="Unit:"+self.parent
                if item.getAttr("var") == "muc#roomconfig_roomname":
                    value=self.name
                if item.getAttr("var") == "muc#roomconfig_presencebroadcast":
                    value="moderator"
                if item.getAttr("var") == "muc#roomconfig_persistentroom":
                    value="1"
                if item.getAttr("var") == "muc#roomconfig_publicroom":
                    value="1"
                if item.getAttr("var") == "muc#roomconfig_moderatedroom":
                    value="0"
                if item.getAttr("var") == "muc#roomconfig_membersonly":
                    value="1"
                if item.getAttr("var") == "muc#roomconfig_passwordprotectedroom":
                    value="0"
                if item.getAttr("var") == "muc#roomconfig_whois":
                    value="anyone" #como es esto??
                if item.getAttr("var") == "muc#roomconfig_changeSubject":
                    value="0"
                if value:
                    node=Node(tag="field", attrs={"var":item.getAttr("var")})
                    valnode=Node(tag="value")
                    valnode.addData(value)
                    node.addChild(node=valnode)
                    x.addChild(node=node)
            query.addChild(node=x)
            iq.addChild(node=query)
            self.myAgent.jabber.send(iq)
            msg = self._receive(True,10)
            if msg and msg.getAttr("type")=="result": #comprobar mejor el mensaje que se devuelve
               #añadiendo los members invitacion
                for agent in self.agentList:
                  iq = Iq(to=self.name+"@"+self.muc_name,typ='set', attrs={"id":self.ID})
                  query = Protocol('query',xmlns="http://jabber.org/protocol/muc#admin")
                  item= Node(tag="item", attrs={"affiliation":"owner","jid":agent})
                  query.addChild(node=item)
                  iq.addChild(node=query)
                  self.myAgent.jabber.send(iq)
                m = Message(to=self.name+"@"+self.muc_name, typ="groupchat")
                sub = Node(tag="subject")
                sub.addData(str(self.goal))
                m.addChild(node=sub)
                self.myAgent.jabber.send(m)
                self.result= True
            else:
                self.result= False

  def checkGoal(self,goalList):
    #falta por implementar
    if goalList!=None:
      return True
    else:
      return False


  def checkType(self):
    types=["Flat","Team","Hierarchy","Bureaucracy","Matrix","Federation","Coalition","Congregation"]
    if self.type in types:
       return True
    return False

  def invite(self,agentList):
    if self.state=="unavailable":
        raise Unavailable
        return
    for agent in agentList:
          message = Node(tag="message", attrs={"to":self.name+"@"+self.muc_name})
          x=Node(tag="x",attrs={"xmlns":"http://jabber.org/protocol/muc#user"})
          y=Node(tag="invite",attrs={"to":agent})
          r=Node(tag="reason")
          r.addData("Inivitation to the Organization "+self.name)
          y.addChild(node=r)
          x.addChild(node=y)
          message.addChild(node=x)
          self.myAgent.jabber.send(message)

  def myJoinRoom(self):
    p = Presence(frm=self.name+"@"+self.muc_name+"/"+self.nick,attrs={"type":"error"})
    t1 = Behaviour.MessageTemplate(p)
    b=self. MyJoinRoomBehaviour(self.muc_name,self.name,self.nick)
    self.myAgent.addBehaviour(b, t1)
    b.join()
    return b.result

  class  MyJoinRoomBehaviour(Behaviour.OneShotBehaviour):
        def __init__(self,muc_name,roomname,nick):
            Behaviour.OneShotBehaviour.__init__(self)
            self.result = False
            self.nick=nick
            self.muc_name=muc_name
            self.name=roomname


        def _process(self):
            p = Presence(to=self.name+"@"+self.muc_name+"/"+self.nick)
            x = Protocol("x", xmlns="http://jabber.org/protocol/muc")
            p.addChild(node=x)
            self.myAgent.jabber.send(p)
            msg=self._receive(True,10)
            if msg:
                    error=msg.getTag("error")
                    if error:
                        self.result = error.getAttr("code")
                        return
            if self.name not in self.myAgent.rooms:
                self.myAgent.rooms.append(self.name)
            self.result = True

  def leave(self):
      """
     Agent leaves and it is removed from the member list
      """
      if self.state=="unavailable":
        raise Unavailable
        return
      if not self.owner:
          if not self.checkIsInUnits():
              units=self.getUnitList()
              units.append(self.name)
              for u in units:
                  p = Presence(to=u+"@"+self.muc_name+"/"+self.nick,typ="unavailable")
                  self.myAgent.jabber.send(p)
                  self.state="unavailable"
                  self.myAgent.removeBehaviour(self.presenceBehaviour)
                  self.myAgent.removeBehaviour(self)
          else:
              raise NotAllowed
      else:
            raise LastOwner


  def getAllUnitList(self):
        list=self.getUnitList()
        return list

  def joinUnit(self,unit):
    if self.state=="unavailable":
        raise Unavailable
        return
    l=self.getAllUnitList()
    if unit.name not in l:
        raise NotValidUnit
        #print unit.name," lista",l
        return
    unit.create=False
    unit.parent=self.name
    result=unit.myJoin()
    if result==True:
        self.myAgent.addBehaviour(unit)
        unit.unitTemplate()
    else:
        raise result



  def checkIsInUnits(self):
      ismember=False
      units=self.getUnitList()
      jid=str(self.myAgent.JID)
      ID="".join([string.ascii_letters[int(random.randint(0,len(string.ascii_letters)-1))] for a in range(5)])
      p = Iq(frm=jid, attrs={"id":ID})
      t1 = Behaviour.MessageTemplate(p)
      b=self.checkIsInUnitsBehaviour(jid,ID)
      self.myAgent.addBehaviour(b, t1)
      b.join()
      b.result
      print b.result
      for u in units:
          if u in b.result:
                  ismember=True
      return ismember

  class checkIsInUnitsBehaviour(Behaviour.OneShotBehaviour):
        def __init__(self,jid,ID):
            Behaviour.OneShotBehaviour.__init__(self)
            self.ID=ID
            self.jid=jid
            self.result=[]

        def _process(self):
          iq = Iq(to=self.jid,typ='get', attrs={"id":self.ID})
          query = Protocol('query',xmlns="http://jabber.org/protocol/disco#items",attrs={"node":"http://jabber.org/protocol/muc#rooms"})
          iq.addChild(node=query)
          self.myAgent.jabber.send(iq)
          msg = self._receive(True,10)
          if msg:
                items =msg.getChildren()
                for item in items:
                    if item.getAttr("jid"):
                        sala=str(item.getAttr("jid"))
                        self.result.append(sala.split('@')[0])





  def addUnit(self,unit):
    """
      Creates a new unit inside an organization
      """
    if self.state=="unavailable":
        raise Unavailable
        return
    if self.checkTypes(self.type,unit.type):
    #un sitwch para aquellas organizaciones donde todos puedan crear unidades
        if self.type!="Matrix" and self.type!="Federation":
          if self.checkCreationPermission():
                 unit.create=True
                 unit.parent=self.name
                 unit.parent_type=self.type
                 if self.orgOwner==None:
                     self.orgOwner=self.getOwner()
                 unit.orgOwner=self.orgOwner
                 unit.create=True
                 result=unit.myCreate()
                 if result==True:
                     self.myAgent.addBehaviour(unit)
                     unit.unitTemplate()
                 else:
                         raise result
          else:
             raise NotCreatePermision
        elif self.checkCreationPermission():
                 unit.create=True
                 unit.parent=self.name
                 unit.parent_type=self.type
                 if self.orgOwner==None:
                     self.orgOwner=self.getOwner()
                 unit.orgOwner=self.orgOwner
                 unit.create=True
                 result=unit.myCreate()
                 if result==True:
                     self.myAgent.addBehaviour(unit)
                     unit.unitTemplate()
                 else:
                         raise result
        else:
                 raise NotSupervisor
    else:
      raise NotValidType

  def checkTypes(self,orgType,unitType):
    if orgType=="Flat":
      return True
    if orgType=="Team" and unitType=="Team":
      return True
    if orgType=="Hierarchy" and unitType=="Hierarchy":
      return True
    if orgType=="Bureaucracy" and unitType=="Hierarchy":
      return True
    if orgType=="Matrix" and unitType=="Hierarchy":
      return True
    if orgType=="Federation" and unitType=="Hierarchy":
      return True
    if orgType=="Coalition" and unitType=="Team":
      return True
    if orgType=="Congregation" and unitType=="Hierarchy":
      return True
    if orgType=="Congregation" and unitType=="Team":
      return True
    if orgType=="Congregation" and unitType=="Flat":
      return True
    return False

  def sendMessage(self,message):
        raise UnavailableFunction

  def sendPrivateMessage(self,recName,message):
        raise UnavailableFunction
  def receive(self):
        raise UnavailableFunction
  def giveVoice(self,nickname):
      raise UnavailableFunction

  def revokeVoice(self,nickname):
      raise UnavailableFunction
  def receiveMessage(self):
      raise UnavailableFunction
  def _process(self):
      pass



  def getOwner(self):
      dad = DF.DfAgentDescription()
      s=DF.ServiceDescription()
      s.setType("ORGANIZATION")
      s.setName(self.name)
      search = self.myAgent.searchService(dad)
      if search:
          dad=search[0]
          return dad.getAID().getName()
      return None


  class PresenceBehaviour(Behaviour.Behaviour):
        def __init__(self,muc_name,roomname,nick,unit):
            Behaviour.Behaviour.__init__(self)
            self.muc_name=muc_name
            self.name=roomname
            self.nick=nick
            self.unit=unit


        def _process(self):
            msg = self._receive(True)
            if msg:
                if msg.getType()=="unavailable":
                    if msg.getRole()=="none" and msg.getFrom()==self.name+"@"+self.muc_name+"/"+self.nick:
                        x=msg.getTag("x")
                        if x:
                            self.unit.state="unavailable"
                            destroy=x.getTag("destroy")
                            if destroy:
                                print "The room "+self.name+" has been destroyed"
                                if self.unit.owner:
                                    #eliminar del df
                                      time.sleep(random.randint(1,10))
                                      dad = DF.DfAgentDescription()
                                      dad.setAID(self.myAgent.getAID())
                                      search = self.myAgent.searchService(dad)
                                      if search:
                                          newdad=DF.DfAgentDescription()
                                          newdad.setAID(self.myAgent.getAID())
                                          for d in search[0].getServices():
                                              if d.getName()!=self.name and d.getType()!="ORGANIZATION" and d.getType()!="UNIT":
                                                  newdad.addService(d)
                                          self.myAgent.deregisterService(dad)
                                          self.myAgent.registerService(newdad)
                        if msg.getStatusCode()=="301":
                                print "You have been baned"
                        if msg.getStatusCode()=="307":
                                print "You have been kicked"
                        #elimnamos las salas que tenemos dentro
                        units=[]
                        dad = DF.DfAgentDescription()
                        dad.setAID(self.myAgent.getAID())
                        ds = DF.ServiceDescription()
                        ds.setType("UNIT")
                        dad.addService(ds)
                        search = self.myAgent.searchService(dad)
                        parent=self.unit.parent+":"+self.unit.name
                        if search:
                              for s in search:
                                  for d in s.getServices():
                                      prop=d.getProperties()
                                      for p in prop:
                                          if p["name"].strip("u'")=="parent" and parent in p["value"].strip("u'"):
                                              units.append(parent+":"+str(d.getName()))
                                          if "Team:" in self.unit.name and (self.unit.parent_type=="Federation" or self.unit.parent_type=="Matrix"):
                                              #si te han explusado del equipo de supervisores añadimos tus salas propias
                                              if p["name"].strip("u'")=="parent" and self.unit.parent== p["value"].strip("u'"):
                                                  units.append(self.unit.parent+":"+str(d.getName()))

                        #units contiene la lista con las unidades descendientes que pertenecen al agente expulsado
                        dad = DF.DfAgentDescription()
                        dad.setAID(self.myAgent.getAID())
                        ds = DF.ServiceDescription()
                        ds.setType("UNIT")
                        dad.addService(ds)
                        search = self.myAgent.searchService(dad)
                        if search:
                            for s in search:
                                  for d in s.getServices():
                                      prop=d.getProperties()
                                      for p in prop:
                                          if p["name"].strip("u'")=="parent" and p["value"].strip("u'") in units:
                                              units.append(str(d.getName()))
                        for u in units:
                              iq = Iq(to=u+"@"+self.muc_name,typ='set')
                              query = Protocol('query',xmlns="http://jabber.org/protocol/muc#owner")
                              item= Node(tag="destroy")
                              query.addChild(node=item)
                              iq.addChild(node=query)
                              self.myAgent.jabber.send(iq)
                        if self.unit.requestBehaviour:
                                      self.myAgent.removeBehaviour(self.unit.requestBehaviour)
                        self.myAgent.removeBehaviour(self.unit)
                        self.myAgent.removeBehaviour(self)
                        #raise Unavailable


class Flat(Organization):
    def __init__(self,agent, nick, name,password=None, goalList=[], agentList=[],contentLanguage="sl",create=True):
        Organization.__init__(self,agent, nick, name, "Flat", goalList, agentList, contentLanguage,create)


    def requestEntryUnit(self,unit,desc=None):
      if self.state=="unavailable":
          raise Unavailable
          return
      if unit not in self.getUnitList():
          raise NotValidUnit
          return
      #consultar en el DF quien es el owner de la organizaciÃ³n
      dad = DF.DfAgentDescription()
      ds = DF.ServiceDescription()
      ds.setType("UNIT")
      ds.setName(unit)
      dad.addService(ds)
      search = self.myAgent.searchService(dad)
      if search:
          owner=search[0].getAID()
          #comportammiento con mensaje ACL solicitando permiso
          ID="".join([string.ascii_letters[int(random.randint(0,len(string.ascii_letters)-1))] for a in range(5)])
          template = Behaviour.ACLTemplate()
          template.setSender(owner)
          template.setPerformative("inform")
          template.setOntology("spade:x:unit")
          template.setProperty("from",unit)
          template.setConversationId(ID)
          t = Behaviour.MessageTemplate(template)
          self.setTemplate(t)
          b=self.RequestEntryBehaviour(owner,unit,desc,ID)
          self.myAgent.addBehaviour(b, t)
          b.join()
          return b.result

    class RequestEntryBehaviour(Behaviour.OneShotBehaviour):
        def __init__(self,owner,roomname,desc,ID):
            Behaviour.OneShotBehaviour.__init__(self)
            self.owner=owner
            self.name=roomname
            self.desc=desc
            self.ID=ID
            self.result=False

        def _process(self):
            msg=ACLMessage.ACLMessage()
            desc={}
            desc["main"]="Entry"
            if self.desc:
                desc["desc"]=self.desc
            msg.setContent(str(desc))
            msg.setPerformative("request")
            msg.setOntology("spade:x:unit")
            if (msg.getSender() == None):
                msg.setSender(self.myAgent.getAID())
            msg.addReceiver(self.owner)
            msg.setProperty("from",self.name)
            msg.setConversationId(self.ID)
            self.myAgent.send(msg)
            ans= self._receive(True,30)
            if ans:
                if "Allowed:" in ans.getContent():
                   self.result=ans.getContent().split(":")[1]


    def setGoal(self,goalList):
        """
        Updates organization goals
        """
        if self.state=="unavailable":
            raise Unavailable
            return
        Organization.setGoal(self,goalList)


##

    def checkCreationPermission(self):
        return True



    def destroy(self):
        if self.state=="unavailable":
            raise Unavailable
            return
        if not self.owner:
            raise NotAllowed
            return
        Organization.destroy(self)

    class PresenceBehaviour(Behaviour.Behaviour):
        def __init__(self,muc_name,roomname,nick,unit):
            Behaviour.Behaviour.__init__(self)
            self.muc_name=muc_name
            self.name=roomname
            self.nick=nick
            self.unit=unit


        def _process(self):
            msg = self._receive(True)
            if msg:
                if msg.getType()=="unavailable":
                    if msg.getRole()=="none" and msg.getFrom()==self.name+"@"+self.muc_name+"/"+self.nick:
                        x=msg.getTag("x")
                        if x:
                            self.unit.state="unavailable"
                            destroy=x.getTag("destroy")
                            if destroy:
                                print "The room "+self.name+" has been destroyed"
                                if self.unit.owner:
                                    #eliminar del df
                                      time.sleep(random.randint(1,10))
                                      dad = DF.DfAgentDescription()
                                      dad.setAID(self.myAgent.getAID())
                                      search = self.myAgent.searchService(dad)
                                      if search:
                                          newdad=DF.DfAgentDescription()
                                          newdad.setAID(self.myAgent.getAID())
                                          for d in search[0].getServices():
                                              if d.getName()!=self.name and d.getType()!="ORGANIZATION" and d.getType()!="UNIT":
                                                  newdad.addService(d)
                                          self.myAgent.deregisterService(dad)
                                          self.myAgent.registerService(newdad)
                        if msg.getStatusCode()=="301":
                                print "You have been baned"
                        if msg.getStatusCode()=="307":
                                print "You have been kicked"
                        #elimnamos las salas que tenemos dentro
                        units=[]
                        dad = DF.DfAgentDescription()
                        dad.setAID(self.myAgent.getAID())
                        ds = DF.ServiceDescription()
                        ds.setType("UNIT")
                        dad.addService(ds)
                        search = self.myAgent.searchService(dad)
                        name=self.unit.name
                        if search:
                              for s in search:
                                  for d in s.getServices():
                                      prop=d.getProperties()
                                      for p in prop:
                                          if p["name"].strip("u'")=="parent" and name in p["value"].strip("u'"):
                                              units.append(str(d.getName()))

                        #units contiene la lista con las unidades descendientes que pertenecen al agente expulsado
                        dad = DF.DfAgentDescription()
                        dad.setAID(self.myAgent.getAID())
                        ds = DF.ServiceDescription()
                        ds.setType("UNIT")
                        dad.addService(ds)
                        search = self.myAgent.searchService(dad)
                        if search:
                            for s in search:
                                  for d in s.getServices():
                                      prop=d.getProperties()
                                      for p in prop:
                                          if p["name"].strip("u'")=="parent":
                                              for u in units:
                                                  if u in p["value"].strip("u'") and d.getName() not in units:
                                                      units.append(str(d.getName()))
                        for u in units:
                              iq = Iq(to=u+"@"+self.muc_name,typ='set')
                              query = Protocol('query',xmlns="http://jabber.org/protocol/muc#owner")
                              item= Node(tag="destroy")
                              query.addChild(node=item)
                              iq.addChild(node=query)
                              self.myAgent.jabber.send(iq)
                        if self.unit.requestBehaviour:
                                      self.myAgent.removeBehaviour(self.unit.requestBehaviour)
                        if self.name in self.myAgent.rooms:
                            self.myAgent.rooms.remove(self.name)
                        self.myAgent.removeBehaviour(self.unit)
                        self.myAgent.removeBehaviour(self)
                        raise Unavailable
                    else:
                            jid=str(msg.getTag("x").getTag("item").getAttr("jid")).split("/")[0]
                            if jid in self.unit.members and str(msg.getFrom()).count("@")==1  and self.name+"@"+self.muc_name in str(msg.getFrom()):
                                  self.unit.members.remove(jid)
                else:
                        jid=str(msg.getTag("x").getTag("item").getAttr("jid")).split("/")[0]
                        if jid not in self.unit.members and str(msg.getFrom()).count("@")==1  and self.name+"@"+self.muc_name in str(msg.getFrom()):
                                  self.unit.members.append(jid)
                                  if self.unit.owner:
                                      self.unit.addModerator(jid)




class Team(Organization):
    def __init__(self,agent, nick, name,password=None, goalList=[], agentList=[],contentLanguage="sl",create=True):
        self.units=0
        Organization.__init__(self,agent, nick, name, "Team", goalList, agentList, contentLanguage,create)


    def requestEntryUnit(self,unit,desc=None):
      if self.state=="unavailable":
          raise Unavailable
          return
      if unit not in self.getUnitList():
          raise NotValidUnit
          return
      #consultar en el DF quien es el owner de la organizaciÃ³n
      dad = DF.DfAgentDescription()
      ds = DF.ServiceDescription()
      ds.setType("UNIT")
      ds.setName(unit)
      dad.addService(ds)
      search = self.myAgent.searchService(dad)
      if search:
          owner=search[0].getAID()
          #comportammiento con mensaje ACL solicitando permiso
          ID="".join([string.ascii_letters[int(random.randint(0,len(string.ascii_letters)-1))] for a in range(5)])
          template = Behaviour.ACLTemplate()
          template.setSender(owner)
          template.setPerformative("inform")
          template.setOntology("spade:x:unit")
          template.setProperty("from",unit)
          template.setConversationId(ID)
          t = Behaviour.MessageTemplate(template)
          self.setTemplate(t)
          b=self.RequestEntryBehaviour(owner,unit,desc,ID)
          self.myAgent.addBehaviour(b, t)
          b.join()
          return b.result

    class RequestEntryBehaviour(Behaviour.OneShotBehaviour):
        def __init__(self,owner,roomname,desc,ID):
            Behaviour.OneShotBehaviour.__init__(self)
            self.owner=owner
            self.name=roomname
            self.desc=desc
            self.ID=ID
            self.result=False

        def _process(self):
            msg=ACLMessage.ACLMessage()
            desc={}
            desc["main"]="Entry"
            if self.desc:
                desc["desc"]=self.desc
            msg.setContent(str(desc))
            msg.setPerformative("request")
            msg.setOntology("spade:x:unit")
            if (msg.getSender() == None):
                msg.setSender(self.myAgent.getAID())
            msg.addReceiver(self.owner)
            msg.setProperty("from",self.name)
            msg.setConversationId(self.ID)
            self.myAgent.send(msg)
            ans= self._receive(True,30)
            if ans:
                if "Allowed:" in ans.getContent():
                   self.result=ans.getContent().split(":")[1]

    def setGoal(self,goalList):
        """
        Updates organization goals
        """
        if self.state=="unavailable":
            raise Unavailable
            return
        if not self.owner:
            raise NotAllowed
            return
        Organization.setGoal(self,goalList)


##

    def checkCreationPermission(self):
        if self.owner==True:
                return True
        else:
                return False

    def addUnit(self,unit):
        if self.state=="unavailable":
            raise Unavailable
            return
        if not self.checkCreationPermission():
            raise NotAllowed
            return
        if self.units==0:
            Organization.addUnit(self,unit)
            self.units=1
        else:
            raise NotAllowed
            return

    def destroy(self):
        if self.state=="unavailable":
            raise Unavailable
            return
        if not self.owner:
            raise NotAllowed
            return
        Organization.destroy(self)






class Coalition(Organization):
    def __init__(self,agent, nick, name,password=None, goalList=[], agentList=[],contentLanguage="sl",create=True):
        Organization.__init__(self,agent, nick, name, "Coalition", goalList, agentList, contentLanguage,create)






    def setGoal(self,goalList):
        """
        Updates organization goals
        """
        if self.state=="unavailable":
            raise Unavailable
            return
        if not self.owner:
            raise NotAllowed
            return
        Organization.setGoal(self,goalList)



    def checkCreationPermission(self):
     if self.owner==True:
                return True
     else:
            adminList=self.getAdminList()
            try:
              adminList.index(self.myAgent.JID)
            except:
                    return False
            return True

    def giveLeadership(self,jid):
        if self.state=="unavailable":
            raise Unit.Unavailable
            return
        if not self.owner:
            raise Unit.NotAllowed
            return
        self.addAdmin(jid)

    def revokeLeadership(self,jid):
        if self.state=="unavailable":
            raise Unit.Unavailable
            return
        if not self.owner:
            raise Unit.NotAllowed
            return
        self.removeAdmin(jid)

    def requestLeadership(self,desc=None):
      if self.state=="unavailable":
          raise Unit.Unavailable
          return
      if self.owner:
          return True
      #consultar en el DF quien es el owner de la organización
      dad = DF.DfAgentDescription()
      ds = DF.ServiceDescription()
      ds.setType("ORGANIZATION")
      ds.setName(self.name)
      dad.addService(ds)
      search = self.myAgent.searchService(dad)
      owner=search[0].getAID()
      #comportammiento con mensaje ACL solicitando permiso
      ID="".join([string.ascii_letters[int(random.randint(0,len(string.ascii_letters)-1))] for a in range(5)])
      template = Behaviour.ACLTemplate()
      template.setSender(owner)
      template.setPerformative("inform")
      template.setOntology("spade:x:unit")
      template.setProperty("from",self.name)
      template.setConversationId(ID)
      t = Behaviour.MessageTemplate(template)
      b=self.RequestLeadershipBehaviour(owner,self.name,desc,ID)
      self.myAgent.addBehaviour(b, t)
      b.join()
      return b.result


    class RequestLeadershipBehaviour(Behaviour.OneShotBehaviour):
        def __init__(self,owner,roomname,desc,ID):
            Behaviour.OneShotBehaviour.__init__(self)
            self.owner=owner
            self.name=roomname
            self.desc=desc
            self.ID=ID
            self.result=False

        def _process(self):
            msg=ACLMessage.ACLMessage()
            desc={}
            desc["main"]="RoomCreation"
            if self.desc:
                desc["desc"]=self.desc
            msg.setContent(str(desc))
            msg.setPerformative("request")
            msg.setOntology("spade:x:unit")
            if (msg.getSender() == None):
                msg.setSender(self.myAgent.getAID())
            msg.addReceiver(self.owner)
            msg.setProperty("from",self.name)
            msg.setConversationId(self.ID)
            self.myAgent.send(msg)
            ans= self._receive(True,30)
            if ans:
                if ans.getContent()=="Allowed":
                   self.result=True

    def leadershipTest(self,sender,desc):
        "Metodo que permite definir cuando se permite la creación de salas. Hay que sobrecargar"
        return False

    def addUnit(self,unit):
        if self.state=="unavailable":
            raise Unavailable
            return
        if not self.checkCreationPermission():
            raise NotAllowed
            return
        Organization.addUnit(self,unit)

    def destroy(self):
        if self.state=="unavailable":
            raise Unavailable
            return
        if not self.owner:
            raise NotAllowed
            return
        Organization.destroy(self)

    class RequestBehaviour(Behaviour.Behaviour):
        def __init__(self,organization):
            Behaviour.Behaviour.__init__(self)
            self.organization=organization

        def _process(self):
            m= self._receive(True)
            if m:
                desc=None
                sender=m.getSender()
                d=eval(m.getContent())
                desc=None
                if d.has_key("desc"): desc=d["desc"]
                ID=m.getConversationId()
                if "RoomCreation"==d["main"]:
                    allow=self.organization.leadershipTest(sender.getName(),desc)
                    if allow:
                        self.organization.addAdmin(sender.getName())
                        msg=ACLMessage.ACLMessage()
                        msg.setContent("Allowed")
                        msg.setPerformative("inform")
                        msg.setOntology("spade:x:unit")
                        msg.setProperty("from",self.organization.name)
                        msg.setConversationId(ID)
                        if (msg.getSender() == None):
                            msg.setSender(self.myAgent.getAID())
                        msg.addReceiver(sender)
                        self.myAgent.send(msg)
                    else:
                        msg=ACLMessage.ACLMessage()
                        msg.setContent("Not-Allowed")
                        msg.setPerformative("inform")
                        msg.setOntology("spade:x:unit")
                        msg.setProperty("from",self.organization.name)
                        msg.setConversationId(ID)
                        if (msg.getSender() == None):
                            msg.setSender(self.myAgent.getAID())
                        msg.addReceiver(sender)
                        self.myAgent.send(msg)








class Congregation(Organization):
    def __init__(self,agent, nick, name,password=None, goalList=[], agentList=[],contentLanguage="sl",create=True):
        self.unit=0
        Organization.__init__(self,agent, nick, name, "Congregation", goalList, agentList, contentLanguage,create)




    def setGoal(self,goalList):
        """
        Updates organization goals
        """
        if self.state=="unavailable":
            raise Unavailable
            return
        if not self.owner:
            raise NotAllowed
            return
        Organization.setGoal(self,goalList)


##

    def checkCreationPermission(self):
     if self.owner==True:
                return True
     else:
            adminList=self.getAdminList()
            try:
              adminList.index(self.myAgent.JID)
            except:
                    return False
            return True

    def giveLeadership(self,jid):
        if self.state=="unavailable":
            raise Unit.Unavailable
            return
        if not self.owner:
            print self.myAgent.getAID().getName()
            print self.owner
            raise Unit.NotAllowed
            return
        self.addAdmin(jid)

    def revokeLeadership(self,jid):
        if self.state=="unavailable":
            raise Unit.Unavailable
            return
        if not self.owner:
            raise Unit.NotAllowed
            return
        self.removeAdmin(jid)

    def requestLeadership(self,desc=None):
      if self.state=="unavailable":
          raise Unit.Unavailable
          return
      if self.owner:
          return True
      #consultar en el DF quien es el owner de la organización
      dad = DF.DfAgentDescription()
      ds = DF.ServiceDescription()
      ds.setType("ORGANIZATION")
      ds.setName(self.name)
      dad.addService(ds)
      search = self.myAgent.searchService(dad)
      owner=search[0].getAID()
      #comportammiento con mensaje ACL solicitando permiso
      ID="".join([string.ascii_letters[int(random.randint(0,len(string.ascii_letters)-1))] for a in range(5)])
      template = Behaviour.ACLTemplate()
      template.setSender(owner)
      template.setPerformative("inform")
      template.setOntology("spade:x:unit")
      template.setProperty("from",self.name)
      template.setConversationId(ID)
      t = Behaviour.MessageTemplate(template)
      b=self.RequestLeadershipBehaviour(owner,self.name,desc,ID)
      self.myAgent.addBehaviour(b, t)
      b.join()
      return b.result


    class RequestLeadershipBehaviour(Behaviour.OneShotBehaviour):
        def __init__(self,owner,roomname,desc,ID):
            Behaviour.OneShotBehaviour.__init__(self)
            self.owner=owner
            self.name=roomname
            self.desc=desc
            self.ID=ID
            self.result=False

        def _process(self):
            msg=ACLMessage.ACLMessage()
            desc={}
            desc["main"]="RoomCreation"
            if self.desc:
                desc["desc"]=self.desc
            msg.setContent(str(desc))
            msg.setPerformative("request")
            msg.setOntology("spade:x:unit")
            if (msg.getSender() == None):
                msg.setSender(self.myAgent.getAID())
            msg.addReceiver(self.owner)
            msg.setProperty("from",self.name)
            msg.setConversationId(self.ID)
            self.myAgent.send(msg)
            ans= self._receive(True,30)
            if ans:
                if ans.getContent()=="Allowed":
                   self.result=True

    def leadershipTest(self,sender,desc):
        "Metodo que permite definir cuando se permite la creación de salas. Hay que sobrecargar"
        return False

    def addUnit(self,unit):
        if self.state=="unavailable":
            raise Unavailable
            return
        if not self.checkCreationPermission():
            raise NotAllowed
            return
        if self.unit==0:
            Organization.addUnit(self,unit)
            self.unit=1
        else:
            raise NotAllowed
    def joinUnit(self,unit):
        if self.state=="unavailable":
            raise Unavailable
            return
        for r in self.myAgent.rooms:
                if r in self.getSubUnitList(self.name):
                    raise NotAllowed
                    return
        Organization.joinUnit(self,unit)

    def destroy(self):
        if self.state=="unavailable":
            raise Unavailable
            return
        if not self.owner:
            raise NotAllowed
            return
        Organization.destroy(self)

    class RequestBehaviour(Behaviour.Behaviour):
        def __init__(self,organization):
            Behaviour.Behaviour.__init__(self)
            self.organization=organization

        def _process(self):
            m= self._receive(True)
            if m:
                desc=None
                sender=m.getSender()
                d=eval(m.getContent())
                desc=None
                if d.has_key("desc"): desc=d["desc"]
                ID=m.getConversationId()
                if "RoomCreation"==d["main"]:
                    allow=self.organization.leadershipTest(sender.getName(),desc)
                    if allow:
                        self.organization.addAdmin(sender.getName())
                        msg=ACLMessage.ACLMessage()
                        msg.setContent("Allowed")
                        msg.setPerformative("inform")
                        msg.setOntology("spade:x:unit")
                        msg.setProperty("from",self.organization.name)
                        msg.setConversationId(ID)
                        if (msg.getSender() == None):
                            msg.setSender(self.myAgent.getAID())
                        msg.addReceiver(sender)
                        self.myAgent.send(msg)
                    else:
                        msg=ACLMessage.ACLMessage()
                        msg.setContent("Not-Allowed")
                        msg.setPerformative("inform")
                        msg.setOntology("spade:x:unit")
                        msg.setProperty("from",self.organization.name)
                        msg.setConversationId(ID)
                        if (msg.getSender() == None):
                            msg.setSender(self.myAgent.getAID())
                        msg.addReceiver(sender)
                        self.myAgent.send(msg)






class Federation(Organization):
    def __init__(self,agent, nick, name,password=None, goalList=[], agentList=[],contentLanguage="sl",create=True):
        self.cont=0
        Organization.__init__(self,agent, nick, name, "Federation", goalList, agentList, contentLanguage,create)

    def myCreate(self):
      if not self.checkGoal(self.goalList):
          return NotValidGoal
      elif not self.checkType():
          return NotValidType
      elif not self.testRoomName():
          return NotValidName
      elif not self.createRoom():
          return CreationError
      else:
          self.state="available"
          if self.agentList!=[]:
        #enviando invitaciones
            self.invite(self.agentList)
     #registrando en el DF
          dad = DF.DfAgentDescription()
          dad.setAID(self.myAgent.getAID())
          search = self.myAgent.searchService(dad)
          if search:
              dad=search[0]
              d = DF.DfAgentDescription()
              d.setAID(self.myAgent.getAID())
              self.myAgent.deregisterService(d)
          else:
              dad = DF.DfAgentDescription()
              dad.setAID(self.myAgent.getAID())
          ds = DF.ServiceDescription()
          ds.setType("ORGANIZATION")
          ds.setName(self.name)
          dad.addService(ds)
          ds = DF.ServiceDescription()
          ds.setType("UNIT")
          ds.setName("Team:"+self.name)
          ds.addProperty({"name":"parent","value":self.name})
          dad.addService(ds)
          res = self.myAgent.registerService(dad)
          cont=0
          while not res and cont<3:
                 res = self.myAgent.registerService(dad)
                 cont=cont+1
          if not res: return CreationError
          self.owner=True
          self.orgOwner=[self.myAgent.JID,self.myAgent.getDF().getName()]
          p = Presence(frm=self.name+"@"+self.muc_name)
          t = Behaviour.MessageTemplate(p)
          self.presenceBehaviour=self.PresenceBehaviour(self.muc_name,self.name,self.nick,self)
          self.myAgent.addBehaviour(self.presenceBehaviour, t)
          template = Behaviour.ACLTemplate()
          template.setProperty("from",self.name)
          template.setPerformative("request")
          template.setOntology("spade:x:unit")
          t = Behaviour.MessageTemplate(template)
          self.requestBehaviour=self.RequestBehaviour(self)
          self.myAgent.addBehaviour(self.requestBehaviour, t)
          if self.createTeam():
              return True
          else:
              return CreationError


    def createTeam(self):
        ID="".join([string.ascii_letters[int(random.randint(0,len(string.ascii_letters)-1))] for a in range(5)])
        p = Presence(frm="Team:"+self.name+"@"+self.muc_name+"/"+self.nick)
        t1 = Behaviour.MessageTemplate(p)
        b=self.CreateTeamBehaviour(ID,self.muc_name,self.name,self.nick,self.contentLanguage,self.goalList,self.agentList)
        self.myAgent.addBehaviour(b, t1)
        b.join()
        if b.result:
          return True
        return False

    class CreateTeamBehaviour(Behaviour.OneShotBehaviour):
        def __init__(self,ID,muc_name,roomname,nick,contentLanguage,goal,agentList):
            Behaviour.OneShotBehaviour.__init__(self)
            self.result = False
            self.ID=ID
            self.nick=nick
            self.muc_name=muc_name
            self.name="Team:"+roomname
            self.parent=roomname
            self.contentLanguage=contentLanguage
            self.type="Team"
            self.goal=goal
            self.agentList=agentList

        def _process(self):
            p = Presence(to=self.name+"@"+self.muc_name+"/"+self.nick)
            x = Protocol("x", xmlns="http://jabber.org/protocol/muc")
            p.addChild(node=x)
            self.myAgent.jabber.send(p)
            msg=self._receive(True,10)
            if msg:
                if msg.getAttr("type")=="error":
                    print "Room creation is restricted"
                    self.result= False
                    return
            else:
                    self.result= False
                    return
            template= Iq(frm=self.name+"@"+self.muc_name, attrs={"id":self.ID})
            t = Behaviour.MessageTemplate(template)
            self.setTemplate(t)
            iq = Iq(to=self.name+"@"+self.muc_name,typ='get', attrs={"id":self.ID})
            query = Protocol('query',xmlns="http://jabber.org/protocol/muc#owner")
            iq.addChild(node=query)
            self.myAgent.jabber.send(iq)
            msg = self._receive(True,10)
            #para descartar los presence anteriores
            while msg and msg.getName()!="iq":
                msg = self._receive(True,10)

          #setting room configuration
            if not msg or msg.getAttr("type")=="error":
                print "No configuration is possible: "
                self.result= False
                return
            #falta por revisar!!!!
            iq = Iq(to=self.name+"@"+self.muc_name,typ='set', attrs={"id":self.ID})
            query = Protocol('query',xmlns="http://jabber.org/protocol/muc#owner")
            x=Node(tag="x", attrs={"xmlns":"jabber:x:data"," type":"submit"})
            resquery=msg.getQueryChildren()[0] #nos quedamos con el hijo de query
            if resquery: items = resquery.getTags("field")
            if resquery==None:
                print "No configuration is possible"
                self.result= False
            for item in items:
                value=None
                if item.getAttr("var"):
                    value=item.getAttr("value") #tomamos el valor
                if item.getAttr("var") == "muc#roomconfig_lang":
                    value=self.contentLanguage
                if item.getAttr("var") == "muc#roomconfig_roomdesc":
                    value=self.type
                if item.getAttr("var") == "muc#roomconfig_roomtype":
                    value=self.parent+":"+self.name
                if item.getAttr("var") == "muc#roomconfig_roomname":
                    value=self.name
                if item.getAttr("var") == "muc#roomconfig_presencebroadcast":
                    value="moderator"
                if item.getAttr("var") == "muc#roomconfig_persistentroom":
                    value="1"
                if item.getAttr("var") == "muc#roomconfig_publicroom":
                    value="1"
                if item.getAttr("var") == "muc#roomconfig_moderatedroom":
                    value="0"
                if item.getAttr("var") == "muc#roomconfig_membersonly":
                    value="1"
                if item.getAttr("var") == "muc#roomconfig_passwordprotectedroom":
                    value="0"
                if item.getAttr("var") == "muc#roomconfig_whois":
                    value="anyone" #como es esto??
                if item.getAttr("var") == "muc#roomconfig_changeSubject":
                    value="0"
                if value:
                    node=Node(tag="field", attrs={"var":item.getAttr("var")})
                    valnode=Node(tag="value")
                    valnode.addData(value)
                    node.addChild(node=valnode)
                    x.addChild(node=node)
            query.addChild(node=x)
            iq.addChild(node=query)
            self.myAgent.jabber.send(iq)
            msg = self._receive(True,10)
            if msg and msg.getAttr("type")=="result": #comprobar mejor el mensaje que se devuelve
               #añadiendo los members invitacion
                for agent in self.agentList:
                  iq = Iq(to=self.name+"@"+self.muc_name,typ='set', attrs={"id":self.ID})
                  query = Protocol('query',xmlns="http://jabber.org/protocol/muc#admin")
                  item= Node(tag="item", attrs={"affiliation":"admin","jid":agent})
                  query.addChild(node=item)
                  iq.addChild(node=query)
                  self.myAgent.jabber.send(iq)
                m = Message(to=self.name+"@"+self.muc_name, typ="groupchat")
                sub = Node(tag="subject")
                sub.addData(str(self.goal))
                m.addChild(node=sub)
                self.myAgent.jabber.send(m)
                self.result= True
            else:
                self.result= False

    def requestEntryUnit(self,unit,desc=None):
      if self.state=="unavailable":
          raise Unavailable
          return
      if unit not in self.getUnitList():
          raise NotValidUnit
          return
      #consultar en el DF quien es el owner de la organizaciÃ³n
      dad = DF.DfAgentDescription()
      ds = DF.ServiceDescription()
      ds.setType("UNIT")
      ds.setName(unit)
      dad.addService(ds)
      search = self.myAgent.searchService(dad)
      if search:
          owner=search[0].getAID()
          #comportammiento con mensaje ACL solicitando permiso
          ID="".join([string.ascii_letters[int(random.randint(0,len(string.ascii_letters)-1))] for a in range(5)])
          template = Behaviour.ACLTemplate()
          template.setSender(owner)
          template.setPerformative("inform")
          template.setOntology("spade:x:unit")
          template.setProperty("from",unit)
          template.setConversationId(ID)
          t = Behaviour.MessageTemplate(template)
          self.setTemplate(t)
          b=self.RequestEntryBehaviour(owner,unit,desc,ID)
          self.myAgent.addBehaviour(b, t)
          b.join()
          return b.result

    class RequestEntryBehaviour(Behaviour.OneShotBehaviour):
        def __init__(self,owner,roomname,desc,ID):
            Behaviour.OneShotBehaviour.__init__(self)
            self.owner=owner
            self.name=roomname
            self.desc=desc
            self.ID=ID
            self.result=False

        def _process(self):
            msg=ACLMessage.ACLMessage()
            desc={}
            desc["main"]="Entry"
            if self.desc:
                desc["desc"]=self.desc
            msg.setContent(str(desc))
            msg.setPerformative("request")
            msg.setOntology("spade:x:unit")
            if (msg.getSender() == None):
                msg.setSender(self.myAgent.getAID())
            msg.addReceiver(self.owner)
            msg.setProperty("from",self.name)
            msg.setConversationId(self.ID)
            self.myAgent.send(msg)
            ans= self._receive(True,30)
            if ans:
                if "Allowed:" in ans.getContent():
                   self.result=ans.getContent().split(":")[1]

    def setGoal(self,goalList):
        """
        Updates organization goals
        """
        if self.state=="unavailable":
            raise Unavailable
            return
        if not self.owner:
            raise NotAllowed
            return
        Organization.setGoal(self,goalList)


##

    def checkCreationPermission(self):
     if self.owner==True:
                return True
     else:
            adminList=self.getAdminList()
            try:
              adminList.index(self.myAgent.JID)
            except:
                    return False
            return True

    def giveSupervision(self,jid):
        if self.state=="unavailable":
            raise Unit.Unavailable
            return
        if not self.owner:
            raise Unit.NotAllowed
            return
        self.addAdmin(jid)
        self.addMemberTeam(jid)

    def revokeSupervision(self,jid):
        if self.state=="unavailable":
            raise Unit.Unavailable
            return
        if not self.owner:
            raise Unit.NotAllowed
            return
        self.removeAdmin(jid)
        self.removeMemberTeam(jid)

    def requestSupervision(self,desc=None):
      if self.state=="unavailable":
          raise Unit.Unavailable
          return
      if self.owner:
          return True
      #consultar en el DF quien es el owner de la organización
      dad = DF.DfAgentDescription()
      ds = DF.ServiceDescription()
      ds.setType("ORGANIZATION")
      ds.setName(self.name)
      dad.addService(ds)
      search = self.myAgent.searchService(dad)
      cont=0
      while not search and cont<3:
          search = self.myAgent.searchService(dad)
          cont=cont+1
      if search:
          owner=search[0].getAID()
          #comportammiento con mensaje ACL solicitando permiso
          ID="".join([string.ascii_letters[int(random.randint(0,len(string.ascii_letters)-1))] for a in range(5)])
          template = Behaviour.ACLTemplate()
          template.setSender(owner)
          template.setPerformative("inform")
          template.setOntology("spade:x:unit")
          template.setProperty("from",self.name)
          template.setConversationId(ID)
          t = Behaviour.MessageTemplate(template)
          b=self.RequestSupervisionBehaviour(owner,self.name,desc,ID)
          self.myAgent.addBehaviour(b, t)
          b.join()
          return b.result
      else:
          raise DFException


    class RequestSupervisionBehaviour(Behaviour.OneShotBehaviour):
        def __init__(self,owner,roomname,desc,ID):
            Behaviour.OneShotBehaviour.__init__(self)
            self.owner=owner
            self.name=roomname
            self.desc=desc
            self.ID=ID
            self.result=False

        def _process(self):
            msg=ACLMessage.ACLMessage()
            desc={}
            desc["main"]="RoomCreation"
            if self.desc:
                desc["desc"]=self.desc
            msg.setContent(str(desc))
            msg.setPerformative("request")
            msg.setOntology("spade:x:unit")
            if (msg.getSender() == None):
                msg.setSender(self.myAgent.getAID())
            msg.addReceiver(self.owner)
            msg.setProperty("from",self.name)
            msg.setConversationId(self.ID)
            self.myAgent.send(msg)
            ans= self._receive(True,30)
            if ans:
                if ans.getContent()=="Allowed":
                   self.result=True

    def supervisionTest(self,sender,desc):
        "Metodo que permite definir cuando se permite la creación de salas. Hay que sobrecargar"
        return False

    def addUnit(self,unit):
        if self.state=="unavailable":
            raise Unavailable
            return
        if not self.checkCreationPermission():
            raise NotAllowed
            return
        if self.cont==0:
            Organization.addUnit(self,unit)
            self.cont=1
        else:
            raise NotAllowed

    def joinUnit(self,unit):
        if self.state=="unavailable":
            raise Unavailable
            return
        else:
            units=self.getSubUnitList(self.name)
            for r in self.myAgent.rooms:
                if r in units:
                    raise NotAllowed
                    return
            Organization.joinUnit(self,unit)

    def joinSupervisorTeam(self,unit):
        if self.state=="unavailable":
            raise Unavailable
            return
        if not self.checkCreationPermission():
            raise NotAllowed
            return
        if unit.type!="Team":
            raise NotValidUnit
            return
        #puede ser que falle por el problema de la lista que no saca el team
        unit.create=False
        unit.parent=self.name
        unit.name="Team:"+self.name
        Organization.joinUnit(self,unit)


    def getUnitList(self):
        list=Organization.getUnitList(self)
        if "Team:"+self.name in list:
            list.remove("Team:"+self.name)
        return list

    def getAllUnitList(self):
        list=Organization.getUnitList(self)
        return list

    def destroy(self):
        if self.state=="unavailable":
            raise Unavailable
            return
        if not self.owner:
            raise NotAllowed
            return
        Organization.destroy(self)

    class RequestBehaviour(Behaviour.Behaviour):
        def __init__(self,organization):
            Behaviour.Behaviour.__init__(self)
            self.organization=organization

        def _process(self):
            m= self._receive(True)
            if m:
                desc=None
                sender=m.getSender()
                d=eval(m.getContent())
                desc=None
                if d.has_key("desc"): desc=d["desc"]
                ID=m.getConversationId()
                if "RoomCreation"==d["main"]:
                    allow=self.organization.supervisionTest(sender.getName(),desc)
                    if allow:
                        self.organization.giveSupervision(sender.getName())
                        msg=ACLMessage.ACLMessage()
                        msg.setContent("Allowed")
                        msg.setPerformative("inform")
                        msg.setOntology("spade:x:unit")
                        msg.setProperty("from",self.organization.name)
                        msg.setConversationId(ID)
                        if (msg.getSender() == None):
                            msg.setSender(self.myAgent.getAID())
                        msg.addReceiver(sender)
                        self.myAgent.send(msg)
                    else:
                        msg=ACLMessage.ACLMessage()
                        msg.setContent("Not-Allowed")
                        msg.setPerformative("inform")
                        msg.setOntology("spade:x:unit")
                        msg.setProperty("from",self.organization.name)
                        msg.setConversationId(ID)
                        if (msg.getSender() == None):
                            msg.setSender(self.myAgent.getAID())
                        msg.addReceiver(sender)
                        self.myAgent.send(msg)


    def addMemberTeam(self,jid):
        iq = Iq(to="Team:"+self.name+"@"+self.muc_name,typ='set')
        query = Protocol('query',xmlns="http://jabber.org/protocol/muc#admin")
        item= Node(tag="item", attrs={"affiliation":"admin","jid":jid})
        query.addChild(node=item)
        iq.addChild(node=query)
        self.myAgent.jabber.send(iq)


    def removeMemberTeam(self,jid):
        iq = Iq(to="Team:"+self.name+"@"+self.muc_name,typ='set')
        query = Protocol('query',xmlns="http://jabber.org/protocol/muc#admin")
        item= Node(tag="item", attrs={"affiliation":"none","jid":jid})
        query.addChild(node=item)
        iq.addChild(node=query)
        self.myAgent.jabber.send(iq)





class Matrix(Organization):
    def __init__(self,agent, nick, name,password=None, goalList=[], agentList=[],contentLanguage="sl",create=True):
        self.cont=0
        Organization.__init__(self,agent, nick, name, "Matrix", goalList, agentList, contentLanguage,create)

    def myCreate(self):
      if not self.checkGoal(self.goalList):
          return NotValidGoal
      elif not self.checkType():
          return NotValidType
      elif not self.testRoomName():
          return NotValidName
      elif not self.createRoom():
          return CreationError
      else:
          self.state="available"
          if self.agentList!=[]:
        #enviando invitaciones
            self.invite(self.agentList)
     #registrando en el DF
          dad = DF.DfAgentDescription()
          dad.setAID(self.myAgent.getAID())
          search = self.myAgent.searchService(dad)
          if search:
              dad=search[0]
              d = DF.DfAgentDescription()
              d.setAID(self.myAgent.getAID())
              self.myAgent.deregisterService(d)
          else:
              dad = DF.DfAgentDescription()
              dad.setAID(self.myAgent.getAID())
          ds = DF.ServiceDescription()
          ds.setType("ORGANIZATION")
          ds.setName(self.name)
          dad.addService(ds)
          ds = DF.ServiceDescription()
          ds.setType("UNIT")
          ds.setName("Team:"+self.name)
          ds.addProperty({"name":"parent","value":self.name})
          dad.addService(ds)
          res = self.myAgent.registerService(dad)
          cont=0
          while not res and cont<3:
                 res = self.myAgent.registerService(dad)
                 cont=cont+1
          if not res: return CreationError
          self.owner=True
          self.orgOwner=[self.myAgent.JID,self.myAgent.getDF().getName()]
          p = Presence(frm=self.name+"@"+self.muc_name)
          t = Behaviour.MessageTemplate(p)
          self.presenceBehaviour=self.PresenceBehaviour(self.muc_name,self.name,self.nick,self)
          self.myAgent.addBehaviour(self.presenceBehaviour, t)
          template = Behaviour.ACLTemplate()
          template.setProperty("from",self.name)
          template.setPerformative("request")
          template.setOntology("spade:x:unit")
          t = Behaviour.MessageTemplate(template)
          self.requestBehaviour=self.RequestBehaviour(self)
          self.myAgent.addBehaviour(self.requestBehaviour, t)
          if self.createTeam():
              return True
          else:
              return CreationError


    def createTeam(self):
        ID="".join([string.ascii_letters[int(random.randint(0,len(string.ascii_letters)-1))] for a in range(5)])
        p = Presence(frm="Team:"+self.name+"@"+self.muc_name+"/"+self.nick)
        t1 = Behaviour.MessageTemplate(p)
        b=self.CreateTeamBehaviour(ID,self.muc_name,self.name,self.nick,self.contentLanguage,self.goalList,self.agentList)
        self.myAgent.addBehaviour(b, t1)
        b.join()
        if b.result:
          return True
        return False

    class CreateTeamBehaviour(Behaviour.OneShotBehaviour):
        def __init__(self,ID,muc_name,roomname,nick,contentLanguage,goal,agentList):
            Behaviour.OneShotBehaviour.__init__(self)
            self.result = False
            self.ID=ID
            self.nick=nick
            self.muc_name=muc_name
            self.name="Team:"+roomname
            self.parent=roomname
            self.contentLanguage=contentLanguage
            self.type="Team"
            self.goal=goal
            self.agentList=agentList

        def _process(self):
            p = Presence(to=self.name+"@"+self.muc_name+"/"+self.nick)
            x = Protocol("x", xmlns="http://jabber.org/protocol/muc")
            p.addChild(node=x)
            self.myAgent.jabber.send(p)
            msg=self._receive(True,10)
            if msg:
                if msg.getAttr("type")=="error":
                    print "Room creation is restricted"
                    self.result= False
                    return
            else:
                    self.result= False
                    return
            template= Iq(frm=self.name+"@"+self.muc_name, attrs={"id":self.ID})
            t = Behaviour.MessageTemplate(template)
            self.setTemplate(t)
            iq = Iq(to=self.name+"@"+self.muc_name,typ='get', attrs={"id":self.ID})
            query = Protocol('query',xmlns="http://jabber.org/protocol/muc#owner")
            iq.addChild(node=query)
            self.myAgent.jabber.send(iq)
            msg = self._receive(True,10)
            #para descartar los presence anteriores
            while msg and msg.getName()!="iq":
                msg = self._receive(True,10)

          #setting room configuration
            if not msg or msg.getAttr("type")=="error":
                print "No configuration is possible: "
                self.result= False
                return
            #falta por revisar!!!!
            iq = Iq(to=self.name+"@"+self.muc_name,typ='set', attrs={"id":self.ID})
            query = Protocol('query',xmlns="http://jabber.org/protocol/muc#owner")
            x=Node(tag="x", attrs={"xmlns":"jabber:x:data"," type":"submit"})
            resquery=msg.getQueryChildren()[0] #nos quedamos con el hijo de query
            if resquery: items = resquery.getTags("field")
            if resquery==None:
                print "No configuration is possible"
                self.result= False
            for item in items:
                value=None
                if item.getAttr("var"):
                    value=item.getAttr("value") #tomamos el valor
                if item.getAttr("var") == "muc#roomconfig_lang":
                    value=self.contentLanguage
                if item.getAttr("var") == "muc#roomconfig_roomdesc":
                    value=self.type
                if item.getAttr("var") == "muc#roomconfig_roomtype":
                    value=self.parent+":"+self.name
                if item.getAttr("var") == "muc#roomconfig_roomname":
                    value=self.name
                if item.getAttr("var") == "muc#roomconfig_presencebroadcast":
                    value="moderator"
                if item.getAttr("var") == "muc#roomconfig_persistentroom":
                    value="1"
                if item.getAttr("var") == "muc#roomconfig_publicroom":
                    value="1"
                if item.getAttr("var") == "muc#roomconfig_moderatedroom":
                    value="0"
                if item.getAttr("var") == "muc#roomconfig_membersonly":
                    value="1"
                if item.getAttr("var") == "muc#roomconfig_passwordprotectedroom":
                    value="0"
                if item.getAttr("var") == "muc#roomconfig_whois":
                    value="anyone" #como es esto??
                if item.getAttr("var") == "muc#roomconfig_changeSubject":
                    value="0"
                if value:
                    node=Node(tag="field", attrs={"var":item.getAttr("var")})
                    valnode=Node(tag="value")
                    valnode.addData(value)
                    node.addChild(node=valnode)
                    x.addChild(node=node)
            query.addChild(node=x)
            iq.addChild(node=query)
            self.myAgent.jabber.send(iq)
            msg = self._receive(True,10)
            if msg and msg.getAttr("type")=="result": #comprobar mejor el mensaje que se devuelve
               #añadiendo los members invitacion
                for agent in self.agentList:
                  iq = Iq(to=self.name+"@"+self.muc_name,typ='set', attrs={"id":self.ID})
                  query = Protocol('query',xmlns="http://jabber.org/protocol/muc#admin")
                  item= Node(tag="item", attrs={"affiliation":"admin","jid":agent})
                  query.addChild(node=item)
                  iq.addChild(node=query)
                  self.myAgent.jabber.send(iq)
                m = Message(to=self.name+"@"+self.muc_name, typ="groupchat")
                sub = Node(tag="subject")
                sub.addData(str(self.goal))
                m.addChild(node=sub)
                self.myAgent.jabber.send(m)
                self.result= True
            else:
                self.result= False


    def setGoal(self,goalList):
        """
        Updates organization goals
        """
        if self.state=="unavailable":
            raise Unavailable
            return
        if not self.owner:
            raise NotAllowed
            return
        Organization.setGoal(self,goalList)


##

    def checkCreationPermission(self):
     if self.owner==True:
                return True
     else:
            adminList=self.getAdminList()
            try:
              adminList.index(self.myAgent.JID)
            except:
                    return False
            return True

    def giveSupervision(self,jid):
        if self.state=="unavailable":
            raise Unit.Unavailable
            return
        if not self.owner:
            raise Unit.NotAllowed
            return
        self.addAdmin(jid)
        self.addMemberTeam(jid)

    def revokeSupervision(self,jid):
        if self.state=="unavailable":
            raise Unit.Unavailable
            return
        if not self.owner:
            raise Unit.NotAllowed
            return
        self.removeAdmin(jid)
        self.removeMemberTeam(jid)

    def requestSupervision(self,desc=None):
      if self.state=="unavailable":
          raise Unit.Unavailable
          return
      if self.owner:
          return True
      #consultar en el DF quien es el owner de la organización
      dad = DF.DfAgentDescription()
      ds = DF.ServiceDescription()
      ds.setType("ORGANIZATION")
      ds.setName(self.name)
      dad.addService(ds)
      search = self.myAgent.searchService(dad)
      cont=0
      while not search and cont<3:
          search = self.myAgent.searchService(dad)
          cont=cont+1
      if search:
          owner=search[0].getAID()
          #comportammiento con mensaje ACL solicitando permiso
          ID="".join([string.ascii_letters[int(random.randint(0,len(string.ascii_letters)-1))] for a in range(5)])
          template = Behaviour.ACLTemplate()
          template.setSender(owner)
          template.setPerformative("inform")
          template.setOntology("spade:x:unit")
          template.setProperty("from",self.name)
          template.setConversationId(ID)
          t = Behaviour.MessageTemplate(template)
          b=self.RequestSupervisionBehaviour(owner,self.name,desc,ID)
          self.myAgent.addBehaviour(b, t)
          b.join()
          return b.result
      else:
          raise DFException


    class RequestSupervisionBehaviour(Behaviour.OneShotBehaviour):
        def __init__(self,owner,roomname,desc,ID):
            Behaviour.OneShotBehaviour.__init__(self)
            self.owner=owner
            self.name=roomname
            self.desc=desc
            self.ID=ID
            self.result=False

        def _process(self):
            msg=ACLMessage.ACLMessage()
            desc={}
            desc["main"]="RoomCreation"
            if self.desc:
                desc["desc"]=self.desc
            msg.setContent(str(desc))
            msg.setPerformative("request")
            msg.setOntology("spade:x:unit")
            if (msg.getSender() == None):
                msg.setSender(self.myAgent.getAID())
            msg.addReceiver(self.owner)
            msg.setProperty("from",self.name)
            msg.setConversationId(self.ID)
            self.myAgent.send(msg)
            ans= self._receive(True,30)
            if ans:
                if ans.getContent()=="Allowed":
                   self.result=True

    def supervisionTest(self,sender,desc):
        "Metodo que permite definir cuando se permite la creación de salas. Hay que sobrecargar"
        return False

    def addUnit(self,unit):
        if self.state=="unavailable":
            raise Unavailable
            return
        if not self.checkCreationPermission():
            raise NotAllowed
            return
        if self.cont==0:
            Organization.addUnit(self,unit)
            self.cont=1
        else:
            raise NotAllowed

    def joinUnit(self,unit):
        if self.state=="unavailable":
            raise Unavailable
            return
        unitList=self.getSubUnitList(unit.name)
        for r in self.myAgent.rooms:
            if r in unitList:
                raise NotAllowed
                return
        Organization.joinUnit(self,unit)

    def joinSupervisorTeam(self,unit):
        if self.state=="unavailable":
            raise Unavailable
            return
        if not self.checkCreationPermission():
            raise NotAllowed
            return
        if unit.type!="Team":
            raise NotValidUnit
            return
        #puede ser que falle por el problema de la lista que no saca el team
        unit.create=False
        unit.parent=self.name
        unit.name="Team:"+self.name
        Organization.joinUnit(self,unit)


    def getUnitList(self):
        list=Organization.getUnitList(self)
        if "Team:"+self.name in list:
            list.remove("Team:"+self.name)
        return list

    def getAllUnitList(self):
        list=Organization.getUnitList(self)
        return list

    def destroy(self):
        if self.state=="unavailable":
            raise Unavailable
            return
        if not self.owner:
            raise NotAllowed
            return
        Organization.destroy(self)

    class RequestBehaviour(Behaviour.Behaviour):
        def __init__(self,organization):
            Behaviour.Behaviour.__init__(self)
            self.organization=organization

        def _process(self):
            m= self._receive(True)
            if m:
                desc=None
                sender=m.getSender()
                d=eval(m.getContent())
                desc=None
                if d.has_key("desc"): desc=d["desc"]
                ID=m.getConversationId()
                if "RoomCreation"==d["main"]:
                    allow=self.organization.supervisionTest(sender.getName(),desc)
                    if allow:
                        self.organization.giveSupervision(sender.getName())
                        msg=ACLMessage.ACLMessage()
                        msg.setContent("Allowed")
                        msg.setPerformative("inform")
                        msg.setOntology("spade:x:unit")
                        msg.setProperty("from",self.organization.name)
                        msg.setConversationId(ID)
                        if (msg.getSender() == None):
                            msg.setSender(self.myAgent.getAID())
                        msg.addReceiver(sender)
                        self.myAgent.send(msg)
                    else:
                        msg=ACLMessage.ACLMessage()
                        msg.setContent("Not-Allowed")
                        msg.setPerformative("inform")
                        msg.setOntology("spade:x:unit")
                        msg.setProperty("from",self.organization.name)
                        msg.setConversationId(ID)
                        if (msg.getSender() == None):
                            msg.setSender(self.myAgent.getAID())
                        msg.addReceiver(sender)
                        self.myAgent.send(msg)


    def addMemberTeam(self,jid):
        iq = Iq(to="Team:"+self.name+"@"+self.muc_name,typ='set')
        query = Protocol('query',xmlns="http://jabber.org/protocol/muc#admin")
        item= Node(tag="item", attrs={"affiliation":"admin","jid":jid})
        query.addChild(node=item)
        iq.addChild(node=query)
        self.myAgent.jabber.send(iq)


    def removeMemberTeam(self,jid):
        iq = Iq(to="Team:"+self.name+"@"+self.muc_name,typ='set')
        query = Protocol('query',xmlns="http://jabber.org/protocol/muc#admin")
        item= Node(tag="item", attrs={"affiliation":"none","jid":jid})
        query.addChild(node=item)
        iq.addChild(node=query)
        self.myAgent.jabber.send(iq)
